//
//  FFSaveImageHandle.m
//  fashionbuyer
//
//  Created by ale tan on 2017/12/28.
//  Copyright © 2017年 ale tan. All rights reserved.
//

#import "FFSaveImageHandle.h"
#import <Photos/Photos.h>
#import "FFTipsView.h"

#import "MBManager.h"

#define TimeOut 10

@implementation FFSaveImageHandle

//保存单张图片到本地
+ (void)saveImage:(UIImage *)image{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        //写入图片到相册
        PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"success = %d, error = %@", success, error);
            if (success) {
//                [FFTipsView showTips:@"保存成功"];
            }
            else{
                [FFTipsView showTips:error.description];
            }
        });
        
    }];
}

//保存多张图片到本地
+ (void)saveImages:(NSArray <__kindof UIImage *>*)images{
    for (UIImage *image in images) {
        [self saveImage:image];
    }
}

//保存单张网络图片到本地
+ (void)saveImageWithUrl:(NSString *)imageUrl{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            if (image) {
                [self saveImage:image];
                [FFTipsView showTips:@"保存成功"];
            }
            else{
                NSLog(@"获取网络图片失败");
                [FFTipsView showTips:@"获取网络图片失败"];
            }
            
        });
    });
}

//保存多张网络图片到本地
+ (void)saveImagesWithUrls:(NSArray *)imageUrls{
    NSMutableArray *imageArr = [NSMutableArray array];
    __block BOOL isTimeOut = NO;
    
    __block NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:TimeOut block:^(NSTimer * _Nonnull timer) {
        [MBManager hideAlert];
        
        isTimeOut = YES;
        
        if (imageArr.count) {
            [self saveImages:imageArr];
        }
        else{
            NSLog(@"获取网络图片失败");
            [FFTipsView showTips:@"获取网络图片失败"];
        }
    } repeats:NO];
    
    [MBManager showLoading];
    
    dispatch_group_t group =  dispatch_group_create();
    
    for (int i=0; i<imageUrls.count; i++) {
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 执行1个耗时的异步操作
            NSString *imageUrl = imageUrls[i];
            if (imageUrl && imageUrl.length) {
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
                UIImage *image = [UIImage imageWithData:data];
                if (image) {
                    [imageArr addObject:image];
                }
            }
        });
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        // 等前面的异步操作都执行完毕后，回到主线程...
        if (!isTimeOut) {
            [timer invalidate];
            timer = nil;
            [MBManager hideAlert];
            if (imageArr.count) {
                [self saveImages:imageArr];
                [FFTipsView showTips:@"保存成功"];
            }
            else{
                NSLog(@"获取网络图片失败");
                [FFTipsView showTips:@"获取网络图片失败"];
            }
        }
    });
}

@end
